import React, { useState, useEffect } from 'react';
import ReactECharts from 'echarts-for-react';
import { Tab, Tabs, TabList, TabPanel } from 'react-tabs';
import 'react-tabs/style/react-tabs.css';
import { exchangeVolume, topCategories, exchangeMethods } from "@/api/service/manageService"
import { DatePicker } from 'antd';
import dayjs from 'dayjs';
import { message } from "antd";

const { RangePicker } = DatePicker;

function Statistics() {
  const [messageApi, contextHolder] = message.useMessage();
  const [selectedIndex, setSelectedIndex] = useState(0);
  const [dates, setDates] = useState<[dayjs.Dayjs, dayjs.Dayjs] | null>([
    dayjs().subtract(8, 'day'),
    dayjs().subtract(1, 'day'),
  ]);

  const [lineChartData, setLineChartData] = useState<any[]>([]);
  const [barChartData, setBarChartData] = useState<any[]>([]);
  const [pieChartData, setPieChartData] = useState<any[]>([]);

  useEffect(() => {
    fetchData();
  }, [dates]); // 当日期范围选择器的值发生变化时，重新获取数据

  useEffect(() => {
    // 初始化加载数据
    fetchData();
  }, []); // 第一次加载组件时，获取默认时间范围的数据

  const fetchData = async () => {
    // 构造发送给服务器的请求数据
    const dateReq = {
      startDate: dates[0].format('YYYY-MM-DD'),
      endDate: dates[1].format('YYYY-MM-DD'),
    };

    try {
      // 发送AJAX请求 - 获取兑换数量折线图数据
      const exchangeVolumeData = await exchangeVolume(dateReq);
      setLineChartData(exchangeVolumeData.datas);

      // 发送AJAX请求 - 获取Top20 品类柱状图数据
      const topCategoriesData = await topCategories(dateReq);
      setBarChartData(topCategoriesData.datas);

      // 发送AJAX请求 - 获取兑换方式饼图数据
      const exchangeMethodsData = await exchangeMethods(dateReq);
      setPieChartData(exchangeMethodsData.datas);
    } catch (err) {
      messageApi.error(err.message);
    }
  }

  const tabStyle = (isSelected: boolean) => ({
    display: 'inline-block',
    padding: '10px 15px',
    cursor: 'pointer',
    background: isSelected ? '#d6caca' : '',
    color: isSelected ? 'rgba(92, 123, 217)' : '',
  });

  const disabledDate = (current: any) => {
    return current && (current >= dayjs().startOf('day') || current < dayjs().subtract(60, 'day').endOf('day'));
  };

  const onDateChange = (dates: any) => {
    if (!dates || dates.length === 0) {
      setDates([
        dayjs().subtract(8, 'days'),
        dayjs().subtract(1, 'days'),
      ]);
    } else {
      setDates(dates);
    }
  };

  const lineChartOption = {
    title: {
      text: '兑换数量折线图',
      left: 'center',
    },
    tooltip: {
      trigger: 'axis',
    },
    xAxis: {
      type: 'category',
      data: lineChartData.map(item => item.date),
    },
    yAxis: {
      type: 'value',
    },
    series: [
      {
        name: '兑换数量',
        type: 'line',
        data: lineChartData.map(item => item.total),
      },
    ],
  };

 const barChartOption = {
  title: {
    text: 'Top20 品类柱状图',
    left: 'center',
  },
  tooltip: {
    trigger: 'axis',
  },
  xAxis: {
    type: 'category',
    data: barChartData.map(item => item.category),
    axisLabel: {
      interval: 0, // 显示所有类别名称，不省略
      rotate: 0, // 文字不倾斜，水平显示
    },
  },
  yAxis: {
    show: false, // 隐藏 y 轴
  },
  series: [
    {
      type: 'bar',
      data: barChartData.map(item => item.total),
      barWidth: '60%', // 控制柱子宽度，比例值
      barGap: '10%', // 控制柱子之间的间隔
      barCategoryGap: '20%', // 控制同一类别柱子之间的间隔
      itemStyle: {
        // 每个柱子的颜色
        color: function(params) {
          const colorList = [
            '#c23531', '#2f4554', '#61a0a8', '#d48265', '#749f83',
            '#ca8622', '#bda29a', '#6e7074', '#546570', '#c4ccd3',
            '#f05b72', '#ef5b9c', '#f47920', '#905a3d', '#fab27b',
            '#2a5caa', '#444693', '#726930', '#b2d235', '#6d8346'
          ];
          return colorList[params.dataIndex % colorList.length];
        }
      },
    },
  ],
};

  const pieChartOption = {
    title: {
      text: '兑换方式饼图',
      left: 'center',
    },
    tooltip: {
      trigger: 'item',
    },
    legend: {
      orient: 'vertical',
      right: 50,
      top: 'middle',
    },
    series: [
      {
        name: '兑换方式',
        type: 'pie',
        radius: '50%',
        data: pieChartData.map(item => ({ value: item.total, name: item.method })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
          },
        },
      },
    ],
  };

  return (
    <div style={{ padding: 10 }}>
      {/* 提示框 */}
      {contextHolder}
      <div style={{ display: 'flex', justifyContent: 'center', marginBottom: '20px' }}>
        <RangePicker
          value={dates}
          onChange={onDateChange}
          disabledDate={disabledDate}
          format="YYYY-MM-DD"
        />
      </div>
      <Tabs selectedIndex={selectedIndex} onSelect={(index: any) => setSelectedIndex(index)}>
        <TabList style={{ borderBottom: '1px solid #e8e8e8', margin: 0, padding: 0, display: 'flex' }}>
          <Tab style={tabStyle(selectedIndex === 0)}>兑换数量折线图</Tab>
          <Tab style={tabStyle(selectedIndex === 1)}>Top20 品类柱状图</Tab>
          <Tab style={tabStyle(selectedIndex === 2)}>兑换方式饼图</Tab>
        </TabList>

        <TabPanel>
          <ReactECharts option={lineChartOption} style={{ height: 400, width: '100%', marginTop: '40px' }} />
        </TabPanel>
        <TabPanel>
          <ReactECharts option={barChartOption} style={{ height: 400, width: '100%', marginTop: '40px' }} />
        </TabPanel>
        <TabPanel>
          <ReactECharts option={pieChartOption} style={{ height: 400, width: '100%', marginTop: '40px' }} />
        </TabPanel>
      </Tabs>
    </div>
  );
}

export default Statistics;


